<template>
  <div class="time-container">
    {{ dateTimeStr }}
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

defineOptions({
  name: "Time",
});

const dateTimeStr = ref("");
let timer: number | null = null;

// 格式化数字为两位数
const formatNumber = (num: number): string => {
  return num < 10 ? `0${num}` : `${num}`;
};

// 更新日期时间
const updateDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = formatNumber(now.getMonth() + 1);
  const day = formatNumber(now.getDate());
  const hours = formatNumber(now.getHours());
  const minutes = formatNumber(now.getMinutes());
  const seconds = formatNumber(now.getSeconds());

  dateTimeStr.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 组件挂载时启动定时器
onMounted(() => {
  updateDateTime(); // 立即更新一次
  timer = window.setInterval(updateDateTime, 1000); // 每秒更新一次
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer !== null) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<style scoped lang="scss">
.time-container {
  color: $menu-text-color;
  font-size: 12px;
}
</style>
